<template>
  <!-- 商品基本信息组件 -->
  <div class="comp">
    <div class="sub-title">基本信息</div>

    <div class="sub-form">
      <el-form :model="form" 
        ref="form"
        label-position="right"
        label-suffix="："
        :label-width="formLabelWidth" 
        :rules="rules" 
      >

        <!-- 商品名称 -->
        <el-form-item label="商品名称" prop="title">
          <div class="flex long-input">
            <el-input v-model="form.title" class="long-input-2" placeholder="请输入商品名称" maxlength="100" show-word-limit style="width: 79%"/>
            <el-input v-model="form.unit" class="short-input mar-l-10" maxlength="6" show-word-limit placeholder="单位，如：个/件/包"/>
          </div>
        </el-form-item>

        <!-- 商品货号 -->
        <el-form-item label="商品货号">
          <el-input v-model="form.goodsCode" class="long-input" placeholder="请输入商品货号" maxlength="100" show-word-limit/>
        </el-form-item>

        <!-- 商品卖点 -->
        <el-form-item label="商品卖点">
          <el-input v-model="form.sellPoint" type="textarea" :rows="3" class="long-input" maxlength="50" show-word-limit/>
        </el-form-item>

        <!-- 商品图片 -->
        <el-form-item label="商品图片" prop="goodsImages">
          <div class="flex pro-p-minheight">
            <draggable v-model="form.goodsImages" 
              dragable="true" 
              :move="getdata"
              @update="datadragEnd">
              <template v-for="(item, key) in form.goodsImages">
                <div class="pic-bar mar-r-30 flex-item" :key="key" @mouseover.stop="itemOver(key)" @mouseout.stop="itemOut(-1)">
                  <div @click="deleteImgages(item,key)">
                    <svg-icon icon-class="close" 
                      :class="{ 'active':key==curIndex || key==curHover }"
                      class="close-icon font-16 noraml-hide" />
                  </div>
                  <img class="picture" :src="item.imageUrl + '?imageView2/1/w/200/h/200/q/100'"/>
                </div>
              </template>
            </draggable>
            <div class="el-upload-box cursor-p"
              @click="platformMaterialCenterVisible = true"
              v-if="form.goodsImages.length < 5">
              <i class="el-icon-plus"></i>
            </div>
          </div>
          <div class="tips mar-t-3">建议尺寸：750*750像素，可以拖拽图片调整顺序，默认第一张为主图</div>
        </el-form-item>

        <!-- 商品来源 -->
        <el-form-item label="商品来源">
          <template v-if="form.goodsSource != '1'">
            <el-select v-model="form.goodsSource" :disabled="true">
              <el-option v-for="(val, key) in dict.goodsSource" :key="key" :label="val" :value="key"></el-option>
            </el-select>
          </template>
          <template v-else>
            <el-select v-model="form.supplierId" :disabled="true">
              <el-option v-for="(item, index) in supplierList" :key="index" :label="item.supplierName" :value="item.supplierId"></el-option>
            </el-select>
          </template>
        </el-form-item>

      </el-form>
    </div>

    <!-- 素材中心dialog -->
    <el-dialog title="平台素材中心" 
      :visible.sync="platformMaterialCenterVisible" 
      :close-on-press-escape="false"
      width="940px" 
    >

      <platform-material-center :showFlag="platformMaterialCenterVisible" 
        :platformType="thirdGoodsObj.platformType" 
        :shopId="thirdGoodsObj.shopId" 
        @callback="openStockDetail = false">
      </platform-material-center>
    </el-dialog>

  </div>
</template>


<script>
  import { getToken } from '@/utils/auth'

  import elDragDialog from '@/directive/el-dragDialog'
  import draggable from 'vuedraggable'
  import goodsBus from '@/views/goods/edit/goods-bus'
  import platformMaterialCenter from '../platform-material-center'

  export default {
    mixins: [goodsBus],
    components: {
      platformMaterialCenter, draggable
    },
    directives: {
      elDragDialog
    },
    props: {
      // 商品对象
      thirdGoodsObj: {
        type: Object
      },
      // 商品属性对象
      propertyObj: {
        type: Object
      },
      formLabelWidth: {
        type: String
      }
    },
    data() {
      // 名称规则
      const titleRule = (rule, value, callback) => {
        if (!this.form.title) {
          return callback(new Error('请填写商品名称'))
        }
        if (!this.form.unit) {
          return callback(new Error('请填写单位'))
        }
        callback()
      }
      // 商品图片规则
      const goodsImagesRule = (rule, value, callback) => {
        if (this.form.goodsImages.length === 0) {
          return callback(new Error('请上传商品图片'))
        }
        callback()
      }
      return {
        curIndex: -1,
        curHover: -1,
        token: {},
        // 表单
        form: {
          sortNo: '0', // 排序
          title: '', // 标题
          unit: '件', // 单位
          goodsCode: '', // 商品货号
          posterTitle: '', // 海报商品名称
          posterRecommend: '', // 海报商品推荐语
          sellPoint: '', // 商品卖点
          shareCopy: '', // 分享文案
          goodsType: '', // 商品类型
          goodsImages: [], // 商品图片列表
          labelTypes: [], // 1: 推荐, 2: 热门,3: 新品4: 包邮
          shareImageUrl: '', // 分享图片
          picUrl: '', // 单列大图
          posterImageUrl: '', // 商品海报
          goodscategoryIds: [], // 商品分类
          wholesaleGoodscategoryIds: [], // 批发商品分类
          goodsSource: '0', // 商品来源 0企业 1供应商 2淘宝商品 3供货联盟
          supplierId: '', // 供应商id
          brandId: '', // 品牌id
          goodsStatus: '0', // 零售商品状态
          wholesaleGoodsStatus: '0', // 批发商品状态
          isGoodsTiming: 0, // 定时上下架开关
          timeUploadOrDown: '', // 定时上下架类型
          openingTime: '' // 定时时间
        },
        // 定时表单
        taskForm: {
          timingCheckedDown: false,
          timingCheckedUp: false,
          viewOpeningTime: '',
          oldTimeUploadOrDown: '', // 临时变量，存储的定时标识
          oldOpeningTime: '' // 临时变量，存储的定时时间
        },
        // 数据字典
        dict: {
          goodsSource: {}
        },
        // 企业配置
        enterpriseConfig: {
          categorySeparate: '0',
          wholesaleCategoryAlias: '0'
        },
        // 表单规则
        rules: {
          title: [
            { required: true, trigger: 'blur', validator: titleRule }
          ],
          goodsImages: [
            { required: true, trigger: 'blur', validator: goodsImagesRule }
          ]
        },
        // 文件loading
        fileLoading: false,
        shareFileLoading: false,
        picFileLoading: false,
        posterFileLoading: false,
        platformMaterialCenterVisible: false,
        // 供应商列表
        supplierList: []
      }
    },
    created() {
    },
    mounted() {
      const goodsBaseData = this.$store.state.goodsBaseData
      Object.assign(this.enterpriseConfig, goodsBaseData.enterpriseConfig)
      Object.assign(this.dict, goodsBaseData.dict)

      this.token = { accessToken: getToken() }
      this.initForm()
    },
    methods: {
      // 初始化表单
      initForm() {
        Object.assign(this.form, this.thirdGoodsObj)
      },
      // 图片上传前校验
      beforeUpload(file, pictureType) {
        const isJPG = file.type === 'image/jpeg'
        const isGIF = file.type === 'image/gif'
        const isPNG = file.type === 'image/png'
        const isBMP = file.type === 'image/bmp'
        if (!isJPG && !isGIF && !isPNG && !isBMP) {
          this.$message.error('上传图片必须是JPG/GIF/PNG/BMP 格式!')
          return false
        }
        if (pictureType === 'goodsImage') {
          this.fileLoading = true
        }
        if (pictureType === 'goodsPicImage') {
          this.picFileLoading = true
        }
        if (pictureType === 'goodsShareImage') {
          this.shareFileLoading = true
        }
        if (pictureType === 'goodsPosterImage') {
          this.posterFileLoading = true
        }
        return true
      },
      // 文件超出个数限制时的钩子
      handleExceed(file, fileList) {
        // debugger
        this.$message({ type: 'error', message: '商品图片最多5张' })
      },
      // 图片上传成功后处理
      handleUploadSuccess(res, file, fileList, pictureType) {
        debugger
        const image = new Image()
        image.src = file.url
        image.onload = () => {
          debugger
          console.log(image.width, image.height)
        }
        if (pictureType === 'goodsImage') {
          this.fileLoading = false
        }
        if (pictureType === 'goodsPicImage') {
          this.picFileLoading = false
        }
        if (pictureType === 'goodsShareImage') {
          this.shareFileLoading = false
        }
        if (pictureType === 'goodsPosterImage') {
          this.posterFileLoading = false
        }

        if (res.code === 101) {
          const imageUrl = res.data[0]
          if (pictureType === 'goodsImage') {
            const goodsImages = this.$utils.deepClone(fileList)
            goodsImages.forEach((item) => {
              if (item.response) {
                item.imageUrl = item.response.data[0]
              }
            })
            this.form.goodsImages = goodsImages
            this.$refs['form'].clearValidate('goodsImages')
          }
          if (pictureType === 'goodsPicImage') {
            this.form.picUrl = imageUrl
          }
          if (pictureType === 'goodsShareImage') {
            this.form.shareImageUrl = imageUrl
          }
          if (pictureType === 'goodsPosterImage') {
            this.form.posterImageUrl = imageUrl
          }
        } else {
          this.$message({ type: 'error', message: res.msg })
        }
      },
      // 拖拽中事件
      getdata(evt) {},
      // 拖拽结束事件
      datadragEnd(evt) {
        evt.preventDefault()
        const filters = this.form.goodsImages
        for (let a = 0; a < filters.length; a++) {
          filters[a].index = a
        }
        this.form.goodsImages = filters
      },
      // 鼠标移入事件
      itemOver(index) {
        this.curHover = index
      },
      // 鼠标移出事件
      itemOut(index) {
        this.curHover = index
      },
      // 删除图片
      deleteImgages(item, key) {
        const goodsImages = this.form.goodsImages
        goodsImages.splice(key, 1)
        this.form.goodsImages = goodsImages
        this.$refs['form'].validateField('goodsImages')
      },
      // 图片删除事件
      closeEls(item) {
        if (item === 'picUrl') {
          this.form.picUrl = ''
        }
        if (item === 'shareImageUrl') {
          this.form.shareImageUrl = ''
        }
        if (item === 'posterImageUrl') {
          this.form.posterImageUrl = ''
        }
      },
      // 表单校验 true：成功 false：失败
      checkForm() {
        let ret = true
        this.$refs['form'].validate((valid, result) => {
          if (!valid) {
            const propKeys = Object.keys(result)
            this.$refs['form'].fields.forEach(field => {
              const index = propKeys.indexOf(field.prop)
              if (index !== -1) {
                this.$emit('addVaildShow', field)
              }
            })
            ret = false
          }
        })
        return ret
      },
      // 提交表单
      submitForm() {
        const submitForm = {
        }
        return submitForm
      }
    }
  }
</script>

<style lang="less" scoped>
  .pro-p-minheight {
    min-height: 148px;
  }
  .noraml-hide {
    display: none !important;
  }
  .active {
    display: block !important;
  }
  .long-input {
    width: 80%;
  }
  .long-input-2 {
    min-width: 55%;
  }
  .short-input {
    width: 20%;
  }
  .default-input {
    width: 50%;
  }
  .tips {
    color: gray;
    font-size: 12px;
    line-height: 1.2;
    padding-top: 5px;
  }
  .picture {
    width: 146px;
    height: 146px;
    display: block;
  }
  .pic-bar {
    position: relative;
    display: inline-block;
    .close-icon {
      position: absolute;
      right: -30px;
      top: -11px;
      width: 31px;
      height: 40px;
      padding: 0 7px;
      cursor: pointer;
    }
    span {
      position: absolute;
      right: 0;
      bottom: 0;
      width: 100%;
      display: block;
      color: #fff;
      text-align: center;
      padding: 3px 0;
      background: rgba(0, 0, 0, 0.5);
      cursor: pointer;
    }
  }

  .el-upload-box {
    text-align: center;
    display: inline-block;
    background-color: #fbfdff;
    border: 1px dashed #c0ccda;
    border-radius: 6px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    width: 146px;
    height: 146px;
    line-height: 146px;
    vertical-align: top;
    i {
      font-size: 28px;
      color: #8c939d;
    }
  }
</style>
